const { default: store } = require("../../utils/store")
import { handleUrlParams, valIsNull } from "../../utils/utils"
import request from "../../plugins/request"

const pageOptions = {
	// 页面数据
	data: {
		isFirstOnShow: true, // 是否为首次执行onShow
		userInfo: {
			xm: "", //姓名
			xb: "", //性别
			mz: "", //民族
			cc: "", //学历
			xh: "", //学号
			ksh: "", // 考生号
			nj: "", //年级
			bjmc: "", //班级名称
			xymc: "", //学院名称
			zymc: "", //专业名称
		},
		needLocation: false, //是否需要定位
		needHandleSignature: false, //是否需要手写签名
		needSfzImageUpload: false, //是否需要上传身份证照片
		lastVerifiedResult: {
			verifyState: 2, //核验状态,0核验失败，1已核验，2未核验
			limitState: false, //限制状态，false不限制，true限制
			limitMsg: "", //限制信息
		},
		template_id: "", //模板id
		template_notice_id: "", //活动通知模板id
		position: {
			//是否限制位置
			limit: false,
		},
		maxRetryCount: -1, //最大重试次数
	},
	// 页面载入时
	onLoad(e) {
		// this.init(e)
	},
	valIsNull,
	// 页面初始化
	init() {
		//获取最大的重试次数
		const maxRetryCount = store.maxRetryCount.get()
		if (
			maxRetryCount !== null &&
			maxRetryCount !== undefined &&
			maxRetryCount !== ""
		) {
			this.setData({
				maxRetryCount: maxRetryCount,
			})
		}
		//从缓存中获取用户信息
		const userInfo = store.userInfo.get()
		if (valIsNull(userInfo)) {
			//跳转到登录页
			wx.showToast({
				title: "登录信息已过期，请重新登录",
				icon: "none",
				duration: 2000,
			})
			wx.redirectTo({
				url: "/informationVerification/pages/login/index/index",
			})
			return
		}
		this.setData({
			userInfo: userInfo,
		})
		wx.showLoading({
			title: "加载中",
		})
		Promise.all([this.checkUser(), this.getLastCheckResult()])
			.then((res) => {
				wx.hideLoading()
			})
			.catch((err) => {
				wx.hideLoading()
				wx.showToast({
					title: err,
					icon: "none",
					duration: 2000,
				})
				console.log(err, "err")
			})
		//清空之前的核验缓存
		store.sfz_back.set("")
		store.sfz_front.set("")
		store.face.set("")
		store.location.set("")
		store.faceImageId.set("")
	},
	//检查用户是否需要核验以及需要核验哪些项目
	checkUser() {
		return new Promise((resolve, reject) => {
			request({
				url: "api/wx/xshy/get-init-params",
				method: "post",
				data: {
					token: store.token.get(),
				},
			})
				.then((res) => {
					const { location, handSignature, sfzImageUpload } = res
					this.setData({
						needLocation: location,
						needHandleSignature: handSignature,
						needSfzImageUpload: sfzImageUpload,
						template_id: res.template_id,
						template_notice_id: res.template_notice_id,
						position: res.position,
					})
					//重置先前的状态
					store.needLocation.set(false)
					store.needHandleSignature.set(false)
					store.needSfzImageUpload.set(false)
					store.locationLimit.set(false)
					store.replaceBg.set(false)

					store.needLocation.set(location)
					store.needHandleSignature.set(handSignature)
					store.needSfzImageUpload.set(sfzImageUpload)
					store.locationLimit.set(res.position)
					store.replaceBg.set(res.replaceBg)
					resolve(res)
				})
				.catch((err) => {
					reject(err)
				})
		})
	},
	//获取上一次核验的结果
	getLastCheckResult() {
		return new Promise((resolve, reject) => {
			request({
				url: "api/wx/xshy/chk-verified-state",
				method: "post",
				data: {
					token: store.token.get(),
				},
			})
				.then((res) => {
					const { verifyState, limitState, limitMsg } = res
					this.setData({
						lastVerifiedResult: {
							verifyState: verifyState,
							limitState: limitState,
							limitMsg: limitMsg,
						},
					})
					store.limitState.set(limitState)
					resolve(res)
				})
				.catch((err) => {
					reject(err)
				})
		})
	},
	//跳转到核验页面
	goToCheck() {
		if (this.data.template_id || this.data.template_notice_id) {
			//询问用户订阅消息模板
			wx.requestSubscribeMessage({
				// tmplIds: [this.data.template_id],
				tmplIds: [this.data.template_id, this.data.template_notice_id],
				success: (res) => {
					console.log(res, "res")
					for (const key in res) {
						//用户拒绝订阅身份验证结果通知模板
						if (key === this.data.template_id &&  res[key] === "reject") {
							wx.showModal({
								title: "提示",
								content:
									"为确保您能及时收到核验结果通知，请点击确定前往设置开启订阅消息通知",
								success: (res) => {
									if (res.confirm) {
										wx.openSetting({
											success: (res) => {
												console.log(res, "打开设置")
											},
										})
									}
								},
							})
							return
						}
					}
					//判断是否需要跳转到位置核验页面
					//如果不需要验证定位信息或者不限制位置范围，直接跳转到身份证核验页面
					//验证不通过和审核不通过的情况不需要再次验证定位信息
					// ![0, 4].includes(this.data.lastVerifiedResult.verifyState)
					if (this.data.needLocation || this.data.position.limit) {
						//跳转到位置验证页面
						wx.navigateTo({
							url: "/informationVerification/pages/getLocation/index",
						})
					} else {
						//判断是否需要上传身份证照片，如果不需要则直接跳转到人脸照片上传页面
						if (this.data.needSfzImageUpload) {
							wx.navigateTo({
								url: "/informationVerification/pages/uploadIdCard/index",
							})
						} else {
							wx.navigateTo({
								url: "/informationVerification/pages/photoInstructions/index",
							})
						}
					}
				},
				fail: (err) => {
					console.log(err, "订阅失败")
					//用户拒绝订阅
					wx.showModal({
						title: "提示",
						content:
							"为确保您能及时收到核验结果通知，请点击确定前往设置开启订阅消息通知",
						success: (res) => {
							if (res.confirm) {
								wx.openSetting({
									success: (res) => {
										console.log(res, "打开设置")
									},
								})
							}
						},
					})
				},
			})
		}
	},
	// 页面准备好时
	onReady() {},
	// 页面显示时
	onShow() {
		this.init()
	},
	// 页面隐藏时
	onHide() {},
	// 页面卸载时
	onUnload() {},
	// 下拉页面时
	onPullDownRefresh() {},
	// 到达页面底部时
	onReachBottom() {},
	// 页面滚动时
	onPageScroll() {},
	// 分享时，注：onShareAppMessage不能为async异步函数，会导致不能及时取得返回值，使得分享设置无效
	onShareAppMessage() {
		/* const title = ''
    const path = ''
    const imageUrl = ``

    return {
      title,
      path,
      imageUrl,
    } */
	},
	//查看核验结果
	viewResult() {
		let auditStatus
		switch (this.data.lastVerifiedResult.verifyState) {
			case 1:
				auditStatus = "pass"
				break
			case 0:
				auditStatus = "reject"
				break
			case 3:
				auditStatus = "doubtAuditPass" //存疑人工审核通过
				break
			case 4:
				auditStatus = "doubtAuditReject" //存疑人工审核不通过
				break
			default:
				auditStatus = this.data.lastVerifiedResult.verifyState
				break
		}
		const url = handleUrlParams(
			"/informationVerification/pages/verificationResult/index",
			{
				auditStatus,
				openType: "1",
			},
		)
		wx.navigateTo({
			url,
		})
	},
	//退出登录
	handleLogout() {
		//确认
		wx.showModal({
			title: "提示",
			content: "确定要退出登录吗？",
			success: (res) => {
				if (res.confirm) {
					//清除登录状态
					store.token.set("")
					store.userInfo.set("")
					//跳转到登录页
					wx.redirectTo({
						url: "/informationVerification/pages/login/index/index",
					})
				}
			},
		})
	},
}

Page(pageOptions)
